package com.netstar.request;

import java.util.HashMap;

import com.netstar.jsonparser.AbstractParser;
import com.netstar.jsonparser.ParserFactory;
import com.netstar.property.ServerError;
import com.netstar.util.EvtLog;

public abstract class UploadFileRequest extends BaseRequest {

	private static final String TAG = "UploadFileRequest";

	@Override
	public String getMethod() {
		return HttpRequest.POST;
	}

	/**
	 * Simply return null here.
	 */
	@Override
	public HashMap<String, String> getData() {
		return null;
	}

	@Override
	protected void onHttpComplete(HttpRequest request) {
		final String content = (String) request.getResponse();
		final int code = request.getResponseCode();
		if (code >= 400 && code <= 499) {
			/*
			 * For 4xx response code, the server will set the error message.
			 */
			AbstractParser parser = ParserFactory.createParser(ParserFactory.TYPE_ERROR, content);
			ServerError se = null;
			try {
				se = (ServerError) parser.parse();
			} catch (Exception e) {
			}
			if (null != se) {
				onFail(se.errorDetail);
			} else {
				onFail(FAIL_MSG_PARSE_SERVER_ERROR);
			}
		} else if (code == 200) {
			AbstractParser parser = ParserFactory.createParser(getParserType(), content);
			Object object = null;
			try {
				object = parser.parse();
			} catch (Exception e) {
				EvtLog.e("UpdateRequest", "url: " + getFinalUrl());
				EvtLog.e("UpdateRequest", "response: " + content);
				EvtLog.e(TAG, e.toString());
			}
			if (null != object) {
				onSuccess(object);
			} else {
				onFail(FAIL_MSG_PARSE_JSON);
			}
		} else {
			// For other request, we simply mark error
			onFail("Server responsed with code " + code);
		}
	}

	public abstract void onSuccess(Object object);

	public abstract int getParserType();
}
